package com.example.educational.service.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.example.educational.controller.utils.BusinessException;
import com.example.educational.controller.utils.Code;
import com.example.educational.controller.utils.SystemException;
import com.example.educational.entity.Attachment;
import com.example.educational.entity.Corporate;
import com.example.educational.entity.User;
import com.example.educational.service.InnerAppService;
import com.example.educational.utils.PrintUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

@Service
public class InnerAppServiceImpl implements InnerAppService {

    @Autowired
    Corporate corporate;


    @Override
    public Boolean sendMessageByButtonInteraction(String toUser, String accessToken, String name, String title, String category, String releaseDate, String imgSrc, String taskId) {
        // 1.准备Url
        String httpF = PrintUtil.JoinStr(corporate.getHttp(), "message/send?access_token=", accessToken);
        // 2.准备请求体
        Map<String, Object> paramMap = new HashMap<>();
        // 2.1添加touser
        paramMap.put("touser", toUser);
        // 2.2添加msgtype
        paramMap.put("msgtype", "template_card");
        // 2.3添加agentid
        paramMap.put("agentid", corporate.getInnerApp().get(0).getAgentId());
        // 2.4添加template_card
        Map<String, Object> templateCardBody = new HashMap<>();
        // 2.4.1添加card_type
        templateCardBody.put("card_type", "button_interaction");
        // 2.4.2添加source
        Map<String, Object> sourceBody = new HashMap<>();
        sourceBody.put("icon_url", "https://wx.qlogo.cn/mmhead/PL5y7QQHZgLTYpXibI8QYjwqyDnnKNKRTIXzCicXDvz72JjV9mIpcxXQ/0");
        sourceBody.put("desc", "教务管理：" + name);
        templateCardBody.put("source", sourceBody);
        // 2.4.3添加action_menu
        Map<String, Object> actionMenuBody = new HashMap<>();
        actionMenuBody.put("desc", "获取当前卡片查看情况");
        ArrayList<Object> actionListBody = new ArrayList<>();
        HashMap<String, String> map1 = new HashMap<>();
        map1.put("text", "已查看人员");
        map1.put("key", "A");
        HashMap<String, String> map2 = new HashMap<>();
        map2.put("text", "未查看人员");
        map2.put("key", "B");
        actionListBody.add(map1);
        actionListBody.add(map2);
        actionMenuBody.put("action_list", actionListBody);
        templateCardBody.put("action_menu", actionMenuBody);
        // 2.4.4添加main_title
        Map<String, Object> mainTitleBody = new HashMap<>();
        mainTitleBody.put("title", title);
        templateCardBody.put("main_title", mainTitleBody);
        // 2.4.5添加quote_area
        Map<String, Object> quoteAreaBody = new HashMap<>();
        quoteAreaBody.put("type", 1);
        quoteAreaBody.put("url", PrintUtil.JoinStr("https://open.weixin.qq.com/connect/oauth2/authorize?appid=wwb1ebbb96788be118&redirect_uri=http://www.lj-txy.love:8081?taskId=", taskId, "&response_type=code&scope=snsapi_privateinfo&state=STATE&agentid=1000002#wechat_redirect"));
        quoteAreaBody.put("quote_text", PrintUtil.JoinStr("通知类型：", category, "\n通知时间：", releaseDate));
        templateCardBody.put("quote_area", quoteAreaBody);
        // 2.4.6添加button_selection
        Map<String, Object> buttonSelectionBody = new HashMap<>();
        buttonSelectionBody.put("question_key", "btn_question_key1");
        buttonSelectionBody.put("title", "当前状态");
        ArrayList<Object> optionListBody = new ArrayList<>();
        HashMap<String, String> map3 = new HashMap<>();
        map3.put("id", "btn_selection_id1");
        map3.put("text", "可查看");
        optionListBody.add(map3);
        buttonSelectionBody.put("option_list", optionListBody);
        buttonSelectionBody.put("selected_id", "btn_selection_id1");
        templateCardBody.put("button_selection", buttonSelectionBody);
        // 2.4.7添加card_action
        Map<String, Object> cardActionMap = new HashMap<>();
        cardActionMap.put("type", 1);
        cardActionMap.put("url", PrintUtil.JoinStr("https://open.weixin.qq.com/connect/oauth2/authorize?appid=wwb1ebbb96788be118&redirect_uri=http://www.lj-txy.love:8081?taskId=", taskId, "&response_type=code&scope=snsapi_privateinfo&state=STATE&agentid=1000002#wechat_redirect"));
        templateCardBody.put("card_action", cardActionMap);
        templateCardBody.put("task_id", taskId);
        // 2.4.8添加button_list
        ArrayList<Object> buttonListBody = new ArrayList<>();
        HashMap map4 = new HashMap<>();
        map4.put("text", "确认查看");
        map4.put("style", 1);
        map4.put("key", "button_key_1");
        buttonListBody.add(map4);
        templateCardBody.put("button_list", buttonListBody);
        paramMap.put("template_card", templateCardBody);
        // 3.添加enable_id_trans
        paramMap.put("enable_id_trans", 0);
        // 4.添加enable_duplicate_check
        paramMap.put("enable_duplicate_check", 1);
        // 5.添加duplicate_check_interval
        paramMap.put("duplicate_check_interval", 1800);
        // 6.将参数转换为JSON
        JSONObject jsonBody = JSONUtil.parseObj(paramMap);
        String response = HttpUtil.post(httpF, jsonBody.toString());
        JSONObject parsedObj = JSONUtil.parseObj(response);
        Object errCode = parsedObj.get("errcode");
        // 判断企业微信是否正确
        if (!"0".equals(errCode.toString())) {
            throw new SystemException(Code.err, parsedObj.get("errmsg").toString());
        }
        return Boolean.TRUE;
    }

    @Override
    public Boolean sendMessageByTextNotice(String toUser, String accessToken, String name, String title, String category, String releaseDate, String imgSrc, String taskId, ArrayList<Attachment> fileSrc) {
        // 1.准备Url
        String httpF = PrintUtil.JoinStr(corporate.getHttp(), "message/send?access_token=", accessToken);
        // 2.准备请求体
        Map<String, Object> paramMap = new HashMap<>();
        // 2.1添加touser
        paramMap.put("touser", toUser);
        // 2.2添加msgtype
        paramMap.put("msgtype", "template_card");
        // 2.3添加agentid
        paramMap.put("agentid", corporate.getInnerApp().get(0).getAgentId());
        // 2.4添加template_card
        Map<String, Object> templateCardBody = new HashMap<>();
        // 2.4.1添加card_type
        templateCardBody.put("card_type", "text_notice");
        // 2.4.2添加source
        Map<String, Object> sourceBody = new HashMap<>();
        sourceBody.put("icon_url", "https://thewindyhill.org/wp-content/uploads/2023/01/GPT3-900x591.jpg");
        sourceBody.put("desc", "教务管理：" + name);
        templateCardBody.put("source", sourceBody);
        // 2.4.3添加main_title
        Map<String, Object> mainTitleBody = new HashMap<>();
        mainTitleBody.put("title", title);
        templateCardBody.put("main_title", mainTitleBody);
        // 2.4.4添加quote_area
        Map<String, Object> quoteAreaBody = new HashMap<>();
        quoteAreaBody.put("type", 1);

        quoteAreaBody.put("url", PrintUtil.JoinStr("https://open.weixin.qq.com/connect/oauth2/authorize?appid=", corporate.getCorpId(), "&redirect_uri=http://", corporate.getInnerApp().get(0).getRedirectUrl(), "/#/home?taskId=", taskId, "&response_type=code&scope=snsapi_base&state=STATE&agentid=", corporate.getInnerApp().get(0).getAgentId(), "#wechat_redirect"));
        quoteAreaBody.put("quote_text", PrintUtil.JoinStr("通知类型：", category, "\n通知时间：", releaseDate));
        templateCardBody.put("quote_area", quoteAreaBody);
        // 2.4.5添加card_action
        Map<String, Object> cardActionMap = new HashMap<>();
        cardActionMap.put("type", 1);
        cardActionMap.put("url", PrintUtil.JoinStr("https://open.weixin.qq.com/connect/oauth2/authorize?appid=", corporate.getCorpId(), "&redirect_uri=http://", corporate.getInnerApp().get(0).getRedirectUrl(), "/#/home?taskId=", taskId, "&response_type=code&scope=snsapi_base&state=STATE&agentid=", corporate.getInnerApp().get(0).getAgentId(), "#wechat_redirect"));
        templateCardBody.put("card_action", cardActionMap);
        templateCardBody.put("task_id", taskId);
        // 2.4.6添加jump_list
        ArrayList<Object> jumpListBody = new ArrayList<>();
        HashMap<String, Object> map1 = new HashMap<>();
        map1.put("type", 1);
        map1.put("title", "已读人员");
        map1.put("url", PrintUtil.JoinStr("https://open.weixin.qq.com/connect/oauth2/authorize?appid=", corporate.getCorpId(), "&redirect_uri=http://", corporate.getInnerApp().get(0).getRedirectUrl(), "/#/readylist?taskId=", taskId, "&response_type=code&scope=snsapi_base&state=STATE&agentid=", corporate.getInnerApp().get(0).getAgentId(), "#wechat_redirect"));
        jumpListBody.add(map1);
        templateCardBody.put("jump_list", jumpListBody);
        HashMap<String, Object> map2 = new HashMap<>();
        map2.put("type", 1);
        map2.put("title", "未读人员");
        map2.put("url", PrintUtil.JoinStr("https://open.weixin.qq.com/connect/oauth2/authorize?appid=", corporate.getCorpId(), "&redirect_uri=http://", corporate.getInnerApp().get(0).getRedirectUrl(), "/#/unreadylist?taskId=", taskId, "&response_type=code&scope=snsapi_base&state=STATE&agentid=", corporate.getInnerApp().get(0).getAgentId(), "#wechat_redirect"));
        jumpListBody.add(map2);
        // 2.4.7添加horizontal_content_list
        int size = fileSrc.size();
        if (size > 0) {
            ArrayList<Object> horizontalContentList = new ArrayList<>();
            for (int i = 0; i < size; i++) {
                HashMap<String, Object> map = new HashMap<>();
                map.put("type", 1);
                map.put("keyname", "附件：");
                map.put("value", fileSrc.get(i).getName());
                map.put("url", fileSrc.get(i).getSrc());
                horizontalContentList.add(map);
            }
            templateCardBody.put("horizontal_content_list", horizontalContentList);
        }
        paramMap.put("template_card", templateCardBody);
        // 3.添加enable_id_trans
        paramMap.put("enable_id_trans", 0);
        // 4.添加enable_duplicate_check
        paramMap.put("enable_duplicate_check", 1);
        // 5.添加duplicate_check_interval
        paramMap.put("duplicate_check_interval", 1800);
        // 6.将参数转换为JSON
        JSONObject jsonBody = JSONUtil.parseObj(paramMap);
        String response = HttpUtil.post(httpF, jsonBody.toString());
        JSONObject parsedObj = JSONUtil.parseObj(response);
        Object errCode = parsedObj.get("errcode");
        // 判断企业微信是否正确
        if (!"0".equals(errCode.toString())) {
            throw new SystemException(Code.err, parsedObj.get("errmsg").toString());
        }
        return Boolean.TRUE;
    }

    @Override
    public ArrayList<String> getDepartmentIds(String accessToken) {
        ArrayList<String> resultLists = new ArrayList<>();
        String httpF = PrintUtil.JoinStr(corporate.getHttp(), "department/simplelist?");
        Map<String, Object> parmMap = new HashMap<>();
        parmMap.put("access_token", accessToken);
        // 发送请求
        String response = HttpUtil.get(httpF, parmMap);
        JSONObject parsedObj = JSONUtil.parseObj(response);
        Object errCode = parsedObj.get("errcode");
        // 判断企业微信是否正确
        if ("0".equals(errCode.toString())) {
            JSONArray parseArr = parsedObj.getJSONArray("department_id");
            for (int i = 0; i < parseArr.size(); i++) {
                JSONObject parseObj = parseArr.getJSONObject(i);
                Object o = parseObj.get("id");
                resultLists.add(String.valueOf(o));
            }
        } else {
            throw new SystemException(Code.err, parsedObj.get("errmsg").toString());
        }
        return resultLists;
    }

    @Override
    public ArrayList<User> getInformationFromDepartment(String accessToken, ArrayList<String> departmentIds) {

        ArrayList<User> userArrayList = new ArrayList<>();
        for (int i = 0; i < departmentIds.size(); i++) {
            String httpF = PrintUtil.JoinStr(corporate.getHttp(), "user/simplelist?");
            Map<String, Object> parmMap = new HashMap<>();
            parmMap.put("access_token", accessToken);
            parmMap.put("department_id", departmentIds.get(i));
            // 发送请求
            String response = HttpUtil.get(httpF, parmMap);
            JSONObject parsedObj = JSONUtil.parseObj(response);
            Object errCode = parsedObj.get("errcode");
            if ("0".equals(errCode.toString())) {
                JSONArray parseArray = parsedObj.getJSONArray("userlist");
                for (int j = 0; j < parseArray.size(); j++) {
                    JSONObject jsonObject = parseArray.getJSONObject(j);
                    String name = (String) jsonObject.get("name");
                    String userId = (String) jsonObject.get("userid");
                }
            } else {
                throw new SystemException(Code.err, parsedObj.get("errmsg").toString());
            }
        }

        return userArrayList;

    }

    @Override
    public ArrayList<User> getInformationFromDepartmentDetail(String accessToken, String departmentId) {
        ArrayList<User> userArrayList = new ArrayList<>();
        String httpF = PrintUtil.JoinStr(corporate.getHttp(), "user/list?");
        Map<String, Object> parmMap = new HashMap<>();
        parmMap.put("access_token", accessToken);
        parmMap.put("department_id", departmentId);
        parmMap.put("fetch_child", 1);
        // 发送请求
        String response = HttpUtil.get(httpF, parmMap);
        JSONObject parsedObj = JSONUtil.parseObj(response);
        Object errCode = parsedObj.get("errcode");
        if ("0".equals(errCode.toString())) {
            JSONArray parseArray = parsedObj.getJSONArray("userlist");
            for (int j = 0; j < parseArray.size(); j++) {
                JSONObject jsonObject = parseArray.getJSONObject(j);
                String name = (String) jsonObject.get("name");
                String id = (String) jsonObject.get("userid");
                Integer role = (Integer) jsonObject.get("isleader");
                User user = new User(id, name, role);
                userArrayList.add(user);
            }
        } else {
            throw new SystemException(Code.err, parsedObj.get("errmsg").toString());
        }
        return userArrayList;
    }


    @Override
    public HashMap<String, Object> getUserIdentify(String accessToken, String code) {
        // 1.获取访问用户身份
        HashMap<String, Object> resultMap = new HashMap<>();
        Object userId;
        Object userTicket;
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("access_token", accessToken);
        paramMap.put("code", code);
        String httpF = PrintUtil.JoinStr(corporate.getHttp(), "auth/", "getuserinfo?");
        // 2.发送请求
        String response = HttpUtil.get(httpF, paramMap);
        JSONObject parsedObj = JSONUtil.parseObj(response);
        Object errCode = parsedObj.get("errcode");
        // 3.判断企业微信是否正确
        if ("0".equals(errCode.toString())) {
            userId = parsedObj.get("userid");
            userTicket = parsedObj.get("user_ticket");
        } else if ("50001".equals(errCode.toString())) {
            throw new BusinessException(Code.err, parsedObj.get("errmsg").toString());
        } else {
            // 非法用户，非法Code
            userId = null;
            userTicket = null;
        }
        resultMap.put("userid", userId);
        resultMap.put("user_ticket", userTicket);
        return resultMap;
    }


    @Override
    public User getUserDetailByUserId(String accessToken, String userId) {
        User user = new User();
        String httpF = PrintUtil.JoinStr(corporate.getHttp(), "user/get?");
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("access_token", accessToken);
        paramMap.put("userid", userId);
        String response = HttpUtil.get(httpF, paramMap);
        JSONObject parsedObj = JSONUtil.parseObj(response);
        Object errCode = parsedObj.get("errcode");
        // 3.判断企业微信是否正确
        if ("0".equals(errCode.toString())) {
            user.setId(parsedObj.get("userid").toString());
            user.setRole((Integer) parsedObj.get("isleader"));
            user.setName(parsedObj.get("name").toString());
        } else {
            throw new SystemException(Code.err, parsedObj.get("errmsg").toString());
        }
        return user;
    }

}
